<template>
  <div>
    <mbao-x item1="用户管理" item2="用户列表"></mbao-x>
    <el-card class="box-card Top">
      <el-row :gutter="12">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="forms.query"
            class="input-with-select"
            @input="Search"
          >
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
          <div class="grid-content bg-purple"></div
        ></el-col>
        <el-col :span="16"
          ><div class="grid-content bg-purple-light">
            <el-button type="primary" @click="Open">添加用户</el-button>
          </div></el-col
        >
      </el-row>
      <!-- 表格 -->
      <el-table :data="tableData" border style="width: 100%" class="Top">
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              style="display: block"
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="Flags(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              icon="el-icon-edit"
              type="primary"
              @click="OpenEdit(scope.row)"
            ></el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="Del(scope.row)"
            ></el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-s-tools"
              @click="Role(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加编辑对话框 -->
      <el-dialog :title="names" :visible.sync="dialogFormVisible">
        <el-form :model="Form" :rules="rules" ref="Form">
          <el-form-item
            label="用户名"
            :label-width="formLabelWidth"
            prop="username"
          >
            <el-input
              v-model="Form.username"
              autocomplete="off"
              :disabled="this.names == '添加用户' ? false : true"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            :label-width="formLabelWidth"
            prop="password"
            v-if="this.names == '添加用户' ? true : false"
          >
            <el-input v-model="Form.password" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" :label-width="formLabelWidth" prop="email">
            <el-input v-model="Form.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item
            label="电话"
            :label-width="formLabelWidth"
            prop="mobile"
          >
            <el-input v-model="Form.mobile" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('Form')"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog title="分配角色" :visible.sync="dialogFormVisibles">
        <el-form :model="form">
          <el-form-item label="当前用户" :label-width="formLabelWidth">
            {{ role.name }}
          </el-form-item>
          <el-form-item label="当前角色" :label-width="formLabelWidth">
            {{ role.roles }}
          </el-form-item>
          <el-form-item label="分配角色" :label-width="formLabelWidth">
            <el-select v-model="form.value" placeholder="请选择活动区域">
              <el-option
                :label="item.roleName"
                :value="item.id"
                v-for="item in option"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisibles = false">取 消</el-button>
          <el-button type="primary" @click="RoleOK">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分页 -->
      <el-pagination
        class="Top"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="forms.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="forms.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
import MbaoX from '../components/MbaoX.vue'
export default {
  components: {
    MbaoX
  },
  data() {
    //   邮箱规则
    var validatePass2 = (rule, value, callback) => {
      const regEmail =
        /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
      if (!regEmail.test(value)) {
        callback(new Error('邮箱格式不正确'))
      } else {
        callback()
      }
    }
    //   电话规则
    var validatePass = (rule, value, callback) => {
      const regMobile = /^1(3|4|5|6|7|8|9)\d{9}$/
      if (!regMobile.test(value)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }
    return {
      role: {
        name: '',
        roles: '',
        id: ''
      },
      // 表格数据
      tableData: [],
      option: [],
      //   获取用户列表数据
      forms: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      form: {
        name: '',
        value: ''
      },
      total: 0,
      EditID: 0,
      formLabelWidth: '80px',
      dialogFormVisible: false,
      dialogFormVisibles: false,
      //   添加用户参数
      Form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      names: '', //判断名字

      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getlist()
  },
  mounted() {},
  methods: {
    async getlist() {
      const res = await this.$http.Users(this.forms)
      console.log(res)
      this.total = res.total
      this.tableData = res.users
    },
    // 分配角色
    async Role(row) {
      this.dialogFormVisibles = true
      const res = await this.$http.Role()
      console.log(res)
      this.option = res
      this.role.name = row.username
      this.role.roles = row.role_name
      this.role.id = row.id
    },
    // 确定分配角色
    async RoleOK() {
      const res = await this.$http.AddRole(this.role.id, {
        rid: this.form.value
      })
      console.log(res)
      this.dialogFormVisibles = false
      this.getlist()
    },
    // 删除
    async Del(row) {
      let Dels
      try {
        Dels = await this.$confirm(
          '此操作将永久删除该文件, 是否继续?',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
      } catch (error) {
        Dels = error
      }
      if (Dels === 'confirm') {
        const res = this.$http.DelUsers(row.id)
        console.log(res)
        this.getlist()
      }
    },
    // 修改用户状态
    async Flags(row) {
      // console.log(val);
      const res = await this.$http.FlagUsers(row.id, row.mg_state)
      console.log(res)
      this.getlist()
    },
    // 添加用户按钮
    Open() {
      this.dialogFormVisible = true
      this.names = '添加用户'
      this.Form = {}
    },
    // 打开编辑
    OpenEdit(row) {
      this.dialogFormVisible = true
      this.names = '编辑用户'
      this.Form = row
      this.EditID = row.id
      //   this.Form = {}
    },
    // 点击确定
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (this.names === '添加用户') {
            const res = await this.$http.AddUsers(this.Form)
            console.log(res)
          } else {
            const res = await this.$http.EditUsers(this.EditID, this.Form)
            console.log(res)
          }
          this.getlist()
          this.dialogFormVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 利用lodash 实现节流 搜索功能
    Search: _.throttle(function () {
      this.getlist()
    }, 3000),
    // 分页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.forms.pagesize = val
      this.getlist()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.forms.pagenum = val
      this.getlist()
    }
  }
}
</script>
<style scoped lang='scss'>
.Top {
  margin-top: 20px;
}
</style>
